import "./style.css";
import React, { useState } from "react";
import "antd/dist/antd.css";

import { Button, Checkbox, Form, Input } from "antd";
import { setAdminInfo } from "../../store/adminSlice";
import { loginAdmin } from "../../api/admin";
import { connect, useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";

const Login = () => {
  const onFinish = (value) => {
    console.log("succee:", value);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  const [user, setuser] = useState("");
  const [pwd, setpwd] = useState("");
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const handlelogin = async () => {
    let res = await loginAdmin({
      name: user,
      pwd: pwd,
    });
    console.log("res", res);

    dispatch(setAdminInfo(res.data));
    navigate("/index", { replace: true });
  };

  return (
    <div className="login">
      <div className="small">
        <Form
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: "请输入用户名!",
              },
            ]}
          >
            <Input
              onChange={(e) => {
                setuser(e.target.value);
              }}
            />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入密码!",
              },
            ]}
          >
            <Input.Password
              onChange={(e) => {
                setpwd(e.target.value);
              }}
            />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Checkbox>记住账号密码</Checkbox>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit" onClick={handlelogin}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
export default Login;
